package com.hzd.service.lol;

import ablaze.framework.api.result.ExecuteResult;
import ablaze.framework.security.verifycode.VerifyCodeService;
import ablaze.framework.service.BaseService;
import ablaze.framework.utils.*;
import com.hzd.entity.lol.LolUser;
import com.hzd.rate.RateSDK;
import com.hzd.rate.RateSDKConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 撸啊撸活动
 *
 * @author christ
 * @date 2015/11/9
 */
@Component
@Transactional
public class LolService extends BaseService {

    @Autowired
    private VerifyCodeService verifyCodeService;

    private static RandomDrawOff randomDrawOff;

    private static String B = "11100";

    private static String M = "1100";

    private static String S = "110";

    static {

        Map map = MapUtils.toMap(1, B, 4, M, 95, S);

        randomDrawOff = new RandomDrawOff(map);

        // 初始化流量发送平台信息
        RateSDKConfig.SERVER_URL = "http://api.tenchang.com/server/";
        RateSDKConfig.APP_KEY = "ffPraMgzhG";
        RateSDKConfig.APP_SECRET = "7LtyMC0bWBxZHisa";
    }


    /**
     * 是否没有参加活动
     *
     * @param openid
     * @return
     */
    public ExecuteResult isNotParticipate(String openid) {
        if (isEmpty(openid)) {
            return failParamNull("请使用微信浏览器打开");
        }

        LolUser wxUser = findUseable(LolUser.class)
                .where()
                .eq("openid", openid)
                .findUnique();

        if (isNotEmpty(wxUser)) {
            return failDataNotExist();
        }
        return success();
    }

    /**
     * 参加活动
     *
     * @param user
     * @return
     */
    public ExecuteResult participate(LolUser user) {

        if (isEmpty(user) || isEmpty(user.getOpenid())) {
            return failParamNull("数据不完整");
        }

        if (isEmpty(user.getVerifyCode())) {
            return failParamNull("短信验证码不能为空");
        }

        if (!verifyCodeService.validate(user.getMobile(), user.getVerifyCode())) {
            return failParamInvalidate("短信验证码错误");
        }

        if (isEmpty(user.getMobile())) {
            return failParamNull("手机号不能为空");
        }

        if (isNotMoblie(user.getMobile())) {
            return failParamInvalidate("手机号格式有误");
        }

        if (isEmpty(user.getBond())) {
            user.setBond("10000");
        }

        LolUser wxUser = findUseable(LolUser.class)
                .where()
                .eq("openid", user.getOpenid())
                .findUnique();

        LolUser mobileUser = findUseable(LolUser.class)
                .where()
                .eq("mobile", user.getMobile())
                .findUnique();

        // 同一个微信号只能参加一次，同一个手机号只能参加一次
        if (isNotEmpty(mobileUser)) {
            return failParamInvalidate("您已参加本活动，不能重复参加哦");
        }

        if (isNotEmpty(wxUser)) {
            return failParamInvalidate("同一个微信用户只能参加一次活动哦");
        }


        // 重置id
        user.setId(null);

        // 体验金都是1000
        user.setTasteMoney("1000");

        // 订单号
        user.setNo(RandomUtils.randomNumeric(28));

        // 随机红包，红包需要在远程注册之前调用
        user.setRedPack(randomRedPack(user.getMobile()));

        // 发送远程注册请求
        remoteRegister(user.getMobile());

        String title = "小撸怡情";
        if (Integer.valueOf(user.getBond()).intValue() >= 5000) {
            title = "强撸灰飞烟灭";
        }

        if (Integer.valueOf(user.getBond()).intValue() <= 1000) {
            title = "大撸伤身";
        }

        // 发送红包
        String no = RedPackSender.send(user.getNo(), title, user.getOpenid(), user.getRedPack());
        user.setRedPackNo(no);

        // 生成流量包
        user.setRate("YD10;DX5;LT20");

        return success(storeAndQuery(user));
    }

    /**
     * 发送流量
     *
     * @param openid
     * @return
     */
    public ExecuteResult sendRate(String openid) {

        if (isEmpty(openid)) {
            return failParamNull("请使用微信浏览器打开");
        }

        LolUser wxUser = findUseable(LolUser.class)
                .where()
                .eq("openid", openid)
                .findUnique();

        if (isEmpty(wxUser)) {
            return failParamInvalidate("您尚未参与活动，请先参与吧");
        }

        if (isEmpty(wxUser.getRateNo())) {
            String no = RateSDK.placeOrder(wxUser.getMobile(), wxUser.getNo(), wxUser.getRate());

            wxUser.setRateNo(no);

            super.store(wxUser);
        }

        return success();
    }

    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    public ExecuteResult sendVerifyCode(String mobile) {

        if (isNotMoblie(mobile)) {
            return failParamInvalidate("手机号格式有误");
        }

        verifyCodeService.send(mobile, "您的短信验证码为：${verifyCode}，请于5分钟之内使用");

        return success();
    }

    /**
     * 随机红包
     *
     * @return
     */
    private String randomRedPack(String mobile) {

        String next = randomDrawOff.getString();

        // 大红包
        if (next.equals(B)) {
            int rowcount = findUseable(LolUser.class)
                    .where()
                    .eq("redPack", B)
                    .startsWith("modifytime", DateUtils.getNowCustomDate())
                    .findRowCount();


            if (rowcount >= 4 || userRegistered(mobile)) {
                return S;
            }
        }

        // 中红包
        if (next.equals(M)) {
            int rowcount = findUseable(LolUser.class)
                    .where()
                    .eq("redPack", M)
                    .startsWith("modifytime", DateUtils.getNowCustomDate())
                    .findRowCount();


            if (rowcount >= 60 || userRegistered(mobile)) {
                return S;
            }
        }

        return next;
    }

    /**
     * 调用远程注册接口
     *
     * @param mobile
     */
    private void remoteRegister(String mobile) {
        String json = HttpUtils.post("http://120.24.99.105:9090/hzd-web-stage/api/v1/user/register", MapUtils.toMap("apikey", "1A3C37P1A0009001A8C00000368280DB", "mobile", mobile));

        if (isEmpty(json)) {
            throw new RuntimeException("注册失败");
        }
    }

    /**
     * 判断用户是否注册
     *
     * @param mobile
     * @return
     */
    private boolean userRegistered(String mobile) {

        String json = HttpUtils.post("http://120.24.99.105:9090/hzd-web-stage/api/v1/user/register", MapUtils.toMap("apikey", "1A3C37P1A0009001A8C00000368280DB", "mobile", mobile));

        if (isEmpty(json)) {
            throw new RuntimeException("注册失败");
        }

        ExecuteResult result = JSONUtils.deserialize(json, ExecuteResult.class);

        if (Integer.valueOf(5000).equals(result.getResultCode())) {
            return true;
        }

        return false;
    }

}
